<template>
  <div ref="editorContainer" style="width: 100%"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as monaco from 'monaco-editor'
import loader from '@monaco-editor/loader'

// SQL关键字和函数列表
const SQL_KEYWORDS = [
  // 关键字
  'SELECT', 'FROM', 'WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT',
  'INSERT INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE FROM', 'JOIN', 'LEFT JOIN',
  'RIGHT JOIN', 'INNER JOIN', 'ON', 'AND', 'OR', 'NOT', 'IN', 'LIKE', 'BETWEEN',
  // 函数
  'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'DISTINCT', 'AS', 'CASE', 'WHEN', 'THEN',
  'ELSE', 'END', 'COALESCE', 'NULLIF', 'CAST', 'CONVERT'
]

// 工具函数
const formatSQL = async (sql) => {
  const response = await fetch('/api/format-sql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ sql })
  })
  const data = await response.json()
  return data.formatted
}

const createSQLSuggestions = (monaco, range) => {
  return SQL_KEYWORDS.map(keyword => ({
    label: keyword,
    kind: monaco.languages.CompletionItemKind.Keyword,
    insertText: keyword,
    detail: '关键字',
    range
  }))
}

const createTableSuggestions = (tables, monaco, range) => {
  return tables.map(table => ({
    label: table.name,
    kind: monaco.languages.CompletionItemKind.Class,
    insertText: table.name,
    detail: '表名',
    documentation: table.description || '',
    range
  }))
}

const createColumnSuggestions = (tables, monaco, range) => {
  return tables.flatMap(table => 
    table.columns?.map(column => ({
      label: column.name,
      kind: monaco.languages.CompletionItemKind.Field,
      insertText: column.name,
      detail: `${table.name} 表字段 (${column.type})`,
      documentation: column.description || '',
      range
    })) || []
  )
}

// Props定义
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'sql'
  },
  options: {
    type: Object,
    default: () => ({})
  },
  height: {
    type: String,
    default: '200px'
  },
  tables: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'mount'])

const editorContainer = ref(null)
let editor = null

// 初始化编辑器
const initializeEditor = async () => {
  if (!editorContainer.value) return

  try {
    const monacoInstance = await loader.init()

    // 注册SQL格式化提供程序
    monacoInstance.languages.registerDocumentFormattingEditProvider('sql', {
      provideDocumentFormattingEdits: (model) => {
        const text = model.getValue()
        const formatted = formatSQLText(text)
        return [{
          range: model.getFullModelRange(),
          text: formatted
        }]
      }
    })

    // 创建编辑器实例
    editor = monacoInstance.editor.create(editorContainer.value, {
      value: props.modelValue,
      language: props.language,
      theme: 'vs',
      automaticLayout: true,
      minimap: { enabled: false },
      fontSize: 14,
      formatOnPaste: true,
      formatOnType: true,
      suggestOnTriggerCharacters: true,
      ...props.options
    })

    // 设置编辑器高度
    editorContainer.value.style.height = props.height

    // 注册SQL语言提示
    monacoInstance.languages.registerCompletionItemProvider('sql', {
      provideCompletionItems: (model, position) => {
        const word = model.getWordUntilPosition(position)
        const range = {
          startLineNumber: position.lineNumber,
          endLineNumber: position.lineNumber,
          startColumn: word.startColumn,
          endColumn: word.endColumn
        }

        return {
          suggestions: [
            ...createSQLSuggestions(monacoInstance, range),
            ...createTableSuggestions(props.tables, monacoInstance, range),
            ...createColumnSuggestions(props.tables, monacoInstance, range)
          ]
        }
      }
    })

    // 内容变化时触发更新
    editor.onDidChangeModelContent(() => {
      const value = editor.getValue()
      emit('update:modelValue', value)
    })

    // 添加格式化功能
    editor.addAction({
      id: 'format-sql',
      label: '格式化SQL',
      keybindings: [
        monacoInstance.KeyMod.Alt | monacoInstance.KeyCode.KeyF
      ],
      run: async (ed) => {
        const value = ed.getValue()
        try {
          const formatted = await formatSQL(value)
          ed.setValue(formatted)
        } catch (error) {
          console.error('Format SQL error:', error)
        }
      }
    })

    // 触发mount事件，传递editor实例
    emit('mount', editor)
  } catch (error) {
    console.error('Monaco editor initialization failed:', error)
  }
}

onMounted(() => {
  initializeEditor()
})

// 监听值的变化
watch(() => props.modelValue, (newValue) => {
  if (editor && newValue !== editor.getValue()) {
    editor.setValue(newValue)
  }
})

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})

// SQL格式化函数
function formatSQLText(sql) {
  // 简单的SQL格式化逻辑
  const keywords = ['SELECT', 'FROM', 'WHERE', 'GROUP BY', 'HAVING', 'ORDER BY',
    'LEFT JOIN', 'RIGHT JOIN', 'INNER JOIN', 'JOIN', 'ON', 'AND', 'OR']
  
  // 将SQL转换为大写关键字
  let formatted = sql.replace(/\b(SELECT|FROM|WHERE|GROUP BY|HAVING|ORDER BY|LEFT JOIN|RIGHT JOIN|INNER JOIN|JOIN|ON|AND|OR)\b/gi,
    match => match.toUpperCase())

  // 在关键字前添加换行
  keywords.forEach(keyword => {
    formatted = formatted.replace(new RegExp(`\\b${keyword}\\b`, 'g'), `\n${keyword}`)
  })

  // 处理缩进
  const lines = formatted.split('\n')
  let indent = 0
  formatted = lines.map(line => {
    line = line.trim()
    if (line.includes(')')) indent--
    const spaces = '  '.repeat(Math.max(0, indent))
    if (line.includes('(')) indent++
    return spaces + line
  }).join('\n')

  return formatted.trim()
}
</script>

<style>
.editor-wrapper {
  width: 100%;
  text-align: left;
  height: 500px;
}
.editor-container {
  width: 100%;
  height: 100%;
}
</style>
